//
//  CouponManager.m
//  takeout
//
//  Created by Mac on 12-12-16.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "CouponManager.h"
#import "ResolveXML.h"
#import "Constants.h"
#import "Coupon.h"

@implementation CouponManager


-(NSArray *) getCouponsByUrl:(NSString *)URIString{
    NSURL *url = [[NSURL alloc] initWithString:[URIString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest* request = [NSMutableURLRequest new];    
    [request setURL:url];    
    [request setHTTPMethod:@"GET"]; 
    NSHTTPURLResponse* response;    
    
    
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; 
    NSString* responseXMLResult=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSError *error;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithXMLString: responseXMLResult options:0 error:&error];
    
    
    
    
    NSArray *children = [doc.rootElement children]; 
    NSMutableArray *result = nil;
    for (GDataXMLElement *element in children) {
        if ([element isKindOfClass:[GDataXMLElement class]]) 
        {
            Coupon *coupon=[[Coupon alloc]init];
            coupon.Id=[[[element childAtIndex:0] stringValue] intValue];
            coupon.Group=[[[element childAtIndex:1] stringValue] intValue];
            coupon.SmallImgUrl=[[element childAtIndex:2] stringValue];
            coupon.LargeImgUrl=[[element childAtIndex:3] stringValue];
            coupon.sort=[[[element childAtIndex:4] stringValue] intValue];
            coupon.Desc=[[element childAtIndex:5] stringValue];
            coupon.CreateTime=[[element childAtIndex:6] stringValue];
            coupon.UpdateTime=[[element childAtIndex:7] stringValue];
            coupon.height=[[[element childAtIndex:8] stringValue] intValue];
            coupon.width=[[[element childAtIndex:9] stringValue] intValue];
            if (result == nil) {
                result = [NSMutableArray arrayWithObject:coupon];
            }else{
                [result addObject:coupon];
            }
            
        }
    } 
    return result;
}
-(NSArray *) getCouponsByCondition:(NSString *)group pageIndex:(NSString *) pageIndex pageSize:(NSString *) pageSize{
    NSString *URIString = [NSString stringWithFormat:SERVICE_DOMAIN, [NSString stringWithFormat: SERVICE_COUPON,group,pageIndex,pageSize]];
    return [self getCouponsByUrl:URIString];
}

@end
